import React from 'react';
import {useDispatch, useSelector} from "react-redux";
import {Avatar, Button, List, Popover} from "antd";
import styles from '../css/LoginAvatar.module.css'
import {UserOutlined} from "@ant-design/icons";
import {changeLoginStatus, setUserInfo} from "../store/modules/userStore";
import {useNavigate} from "react-router-dom";

function LoginAvatar(props) {
    const {isLogin} = useSelector(state => state.user)
    let loginStatus = null
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const handleListClick = (item) => {
        if (item === '个人中心') {
            navigate('/personal')
        } else {
            localStorage.removeItem('userToken')
            dispatch(setUserInfo({}))
            dispatch(changeLoginStatus(false))
            navigate('/')
        }
    }
    if (isLogin) {
        // 登录
        const content = (
            <List
                dataSource={['个人中心', '退出登录']}
                renderItem={(item) => {
                    return (
                        <List.Item style={{cursor: 'pointer'}} onClick={()=>handleListClick(item)}>{item}</List.Item>
                    )
                }}
            />
        )
        loginStatus = (
            <Popover content={content} trigger="hover" placement="bottom">
                <Avatar className={styles.avatarContainer} icon={<UserOutlined/>}/>
            </Popover>
        )
    } else {
        // 未登录
        loginStatus = (
            <Button type="primary" onClick={props.handleLogin}>登录/注册</Button>
        )
    }
    return (
        <div>
            {loginStatus}
        </div>
    );
}

export default LoginAvatar;